#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""A class to handle match results returned via the TaskQUeue"""
# Override use of default Django version by explicitly setting version to use.
# See: http://code.google.com/appengine/docs/python/tools/libraries.html#Django
from google.appengine.dist import use_library
use_library('django', '1.2')

import logging
import sets
import sys

from common.dbclasses import MessageToMatch

from google.appengine.api import prospective_search
from google.appengine.api import xmpp

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util


class MatchResult(webapp.RequestHandler):
  """Processes results delivered via a TaskQueue."""

  def post(self):
    # A message may match more than one subscription for a single user so we
    # use a Set to de-duplicate the jids returned in subscription ids.
    subscribers = sets.Set()
    for sub_id in self.request.get_all('id'):
      subscribers.add(sub_id.split('/')[0])

    doc = prospective_search.get_document(self.request)
    if isinstance(doc, MessageToMatch):
      if doc.snippet:
        snippet = doc.snippet
      else:
        logging.info("No snippet for message from: " + doc.follow)
        return
      try:
        xmpp.send_message(subscribers, snippet)
      except:
        logging.info('Send failed.')
      else:
        logging.info('Message: %s sent to: %s' % (snippet, str(subscribers)))
    else:
      logging.error('Unexpected document type received.')


def main(argv):
  application = webapp.WSGIApplication(
      [('/_ah/prospective_search', MatchResult),
      ], debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main(sys.argv)
